# -*- coding: utf8 -*-
from flask import redirect
from flask.blueprints import Blueprint
from flask.helpers import make_response
from flask.templating import render_template
from flask_restful import abort
from flaskext.wtf.form import Form
from wtforms import TextField
from jinja2.exceptions import TemplateNotFound
from ned_app.nmj_access import getNMJInterface
from nmj.abstract import MediaFile
import logging
import os



LOGGER = logging.getLogger(__name__)
lib_blueprint = Blueprint('library', __name__,
					template_folder='library/templates', static_folder='library/static', url_prefix="/library")
lib_blueprint._static_url_path = lib_blueprint.static_url_path


#@blueprint.route('/library/', defaults={'lib_id': 'index'})
@lib_blueprint.route('/<lib_id>')
def show_library(lib_id):
	LOGGER.info("show page %s from main blueprint", lib_id)
	result = []
	nmj = getNMJInterface()
	for media in nmj.get_shows(lib_id):
		result.append(media.jsondetails())
	#LOGGER.info("get_movies result : %s", result)
	try:
		return render_template('pages/library.html', library=lib_id, movies = sorted(result, key=lambda movie: movie["search_title"]))
	except TemplateNotFound:
		LOGGER.error("Cannot find template pages/library.html")
		abort(404)

@lib_blueprint.route('/<lib_id>/details/nmj_database/media/video/poster/<poster_filename>')
@lib_blueprint.route('/<lib_id>/nmj_database/media/video/poster/<poster_filename>')
def get_poster(lib_id, poster_filename):
	nmj = getNMJInterface()
	resp = make_response(open(os.path.join(nmj.get_library(lib_id).base_dir, "nmj_database/media/video/poster", poster_filename)).read())
	resp.content_type = "image/jpeg"
	return resp

@lib_blueprint.route('/<lib_id>/details/<show_id>')
def show_movie_details(lib_id, show_id):
	nmj = getNMJInterface()
	video = nmj.get_video(lib_id=lib_id, show_id=show_id)
	show = nmj.get_show(lib_id=lib_id, show_id=show_id)
	#LOGGER.debug("show json: %s", show.jsondetails())
	return render_template("pages/details.html", library=lib_id, filename=video.basename, **show.jsondetails())

class SearchMediaForm(Form):
	searchtitle = TextField('searchtitle', validators = [])


@lib_blueprint.route("/<lib_id>/details/<show_id>/searchbytitle/<title>", methods = ['GET', 'POST'])
def search_title(lib_id, show_id, title):
	result = []
	nmj = getNMJInterface()
	LOGGER.info("Searching for media '%s'", title)
	for media in nmj.search(lib_id, "%s.avi" % title):
		export = media.export()
		#LOGGER.debug("media %s export : %s", media, export)
		result.append(export)
	#LOGGER.debug("search result: %s", result)
	form = SearchMediaForm()
	if form.is_submitted():
		return redirect("/library/%s/details/%s/searchbytitle/%s" % (lib_id, show_id, form.searchtitle.data))
	LOGGER.info("Form text is : %s", form.searchtitle)
	return render_template('pages/search_result.html', library=lib_id, movies = result, show_id=show_id, form=form)
	
	
@lib_blueprint.route('/<lib_id>/change/<show_id>/<new_id>')
def change_movie(lib_id, show_id, new_id):
	nmj = getNMJInterface()
	video = nmj.get_video(lib_id=lib_id, show_id=show_id)
	media=MediaFile(video.full_path, video.relative_path)
	nmj.clean_media(lib_id, media)
	show_id = nmj.add_media(lib_id, media, new_id)
	#show = nmj.get_show(lib_id=lib_id, show_id=show_id)
	return redirect("/library/%s/details/%s" % (lib_id, show_id))
	#return render_template("pages/details.html", library=lib_id, **show.jsondetails())

@lib_blueprint.route('/<lib_id>/details/<show_id>/movies', methods = ['GET', 'POST'])
def research_movie(lib_id, show_id):
	result = []
	nmj = getNMJInterface()
	video = nmj.get_video(lib_id=lib_id, show_id=show_id)
	for media in nmj.search(lib_id, video.basename):
		export = media.export()
		#LOGGER.debug("media %s export : %s", media, export)
		result.append(export)
	#LOGGER.debug("search result: %s", result)
	form = SearchMediaForm()
	
	if form.is_submitted():
		LOGGER.info("Form submitted text is : %s", form.searchtitle)
		return redirect("/library/%s/details/%s/searchbytitle/%s" % (lib_id, show_id, form.searchtitle.data))
	LOGGER.info("Form text is : %s", form.searchtitle)
	return render_template('pages/search_result.html', library=lib_id, movies = result, show_id=show_id, form=form)

@lib_blueprint.route('/<lib_id>/details/<show_id>/wallpapers')
def research_wallpapers(lib_id, show_id):
	result = []
	nmj = getNMJInterface()
	details = nmj.get_details(lib_id, show_id)
	for rank, wallpaper in enumerate(details.wallpapers):
		wallpaper.image_id = rank
		result.append(wallpaper)
	return render_template('pages/choose_image.html', library=lib_id, images = result, show_id=show_id, image_type="wallpaper")
	
@lib_blueprint.route('/<lib_id>/details/<show_id>/posters')
def research_posters(lib_id, show_id):
	result = []
	nmj = getNMJInterface()
	details = nmj.get_details(lib_id, show_id)
	for rank, poster in enumerate(details.posters):
		poster.image_id = rank
		result.append(poster)
	return render_template('pages/choose_image.html', library=lib_id, images = result, show_id=show_id, image_type="poster")
	
@lib_blueprint.route('/<lib_id>/change/<show_id>/wallpaper/<int:image_id>')
def change_wallpaper(lib_id, show_id, image_id):
	nmj = getNMJInterface()
	details = nmj.get_details(lib_id, show_id)
	wallpaper = details.wallpapers[image_id]
	nmj.change_wallpaper(lib_id, show_id, wallpaper)
	return redirect("/library/%s/details/%s" % (lib_id, show_id))

@lib_blueprint.route('/<lib_id>/change/<show_id>/poster/<int:image_id>')
def change_poster(lib_id, show_id, image_id):
	nmj = getNMJInterface()
	details = nmj.get_details(lib_id, show_id)
	poster = details.posters[image_id]
	LOGGER.info("Poster choosen is %s", poster)
	nmj.change_poster(lib_id, show_id, poster)
	return redirect("/library/%s/details/%s" % (lib_id, show_id))

def get_blueprint():
	return lib_blueprint


